package com.aos.erp.manager.service.sys.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aos.erp.common.bean.IPageBean;
import com.aos.erp.common.bean.ResultBean;
import com.aos.erp.common.dao.mapper.Condition;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.manager.enums.IsDel;
import com.aos.erp.manager.enums.sys.DepartmentType;
import com.aos.erp.manager.enums.sys.SchoolType;
import com.aos.erp.manager.enums.sys.UserStatus;
import com.aos.erp.manager.enums.sys.UserType;
import com.aos.erp.manager.mapper.sys.*;
import com.aos.erp.manager.model.sys.*;
import com.aos.erp.manager.model.sys.dto.UserDto;
import com.aos.erp.manager.model.sys.vo.SchoolUserVo;
import com.aos.erp.manager.model.sys.vo.UserVo;
import com.aos.erp.manager.remote.model.SynUser;
import com.aos.erp.manager.remote.sys.OrganizationService;
import com.aos.erp.manager.remote.sys.SynRoleService;
import com.aos.erp.manager.remote.sys.SynUserService;
import com.aos.erp.manager.service.mq.SendMessageService;
import com.aos.erp.manager.service.sys.UserService;
import com.aos.erp.manager.util.PasswordUtils;
import com.aos.erp.manager.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DepartmentUserMapper departmentUserMapper;
    @Resource
    private PositionUserMapper positionUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SendMessageService sendMessageService;
    @Resource
    SynUserService synUserService;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    OrganizationService organizationService;
    @Resource
    SynRoleService synRoleService;

    @Override
    public Map<String, Object> addBean(UserVo userVo, String appCode) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", userVo.getUsername());
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user != null) {
            throw new BizException("账号已存在");
        }

        //用户
        user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        String password = PasswordUtils.createPassWord(8);
        //String ciphertext = PasswordUtils.getSaltMD5(password, slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);
        user.setType(Integer.valueOf(UserType.aos.getValue().toString()));
        userMapper.insertObject(user);
        Long userId = user.getId();
        //用户部门
        DepartmentUser departmentUser = new DepartmentUser();
        departmentUser.setDepId(dep.getId());
        departmentUser.setUserId(userId);
        departmentUserMapper.insert(departmentUser);
        //用户岗位
        PositionUser positionUser = new PositionUser();
        positionUser.setPositionId(userVo.getPositionId());
        positionUser.setUserId(userId);
        positionUserMapper.insert(positionUser);

        //TODO 同步用户
        //sendMessageService.synUserInfo(synUser(user, appCode, dep.getDepCode()));
        addUser(user, appCode, dep.getDepCode(), userVo.getRoleId(), 0);

        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", password);
        return map;
    }

    /**
     * 新增用户及关联角色
     *
     * @param user
     * @param appCode 应用code
     * @param depCode 部门code
     * @param roleId  角色id
     * @param type    0:新增  1:修改
     * @throws Exception
     */
    public void addUser(User user, String appCode, String depCode, String roleId, int type) throws Exception {
        ResultBean organization = organizationService.queryByCodes(depCode);
        if (ResultBean.CODE_FAIL == organization.getCode()) {
            throw new BizException(organization.getErrMsg());
        }
        Map<String, Object> map = (Map<String, Object>) organization.getData();
        Long orgId = Long.valueOf(map.get("id").toString());

        Condition condition = new Condition(User.class);
        condition.eqFiled("id", user.getOperatorId());
        User userOperator = baseMapper.selectOne(condition.getWrapper());
        if (userOperator == null) {
            throw new BizException("登录人不存在");
        }

        com.aos.erp.manager.remote.model.User userRole = new com.aos.erp.manager.remote.model.User();
        userRole.setAppCode(appCode);
        List<String> orgNameList = new ArrayList<>();
        orgNameList.add(map.get("name").toString());
        userRole.setOrgNameList(orgNameList);
        List<Long> orgIdList = new ArrayList<>();
        orgIdList.add(Long.valueOf(orgId.toString()));
        userRole.setOrgIdList(orgIdList);
        List<Long> roleIdList = new ArrayList<>();
        roleIdList.add(Long.valueOf(roleId));
        userRole.setRoleIdList(roleIdList);
        // List<String> roleNameList= new ArrayList<>();
        userRole.setName(user.getName());
        userRole.setUsername(user.getUsername());
        userRole.setPassword(user.getPassword());
        userRole.setSalt(user.getSalt());
        userRole.setUsernames(appCode + "+" + userOperator.getUsername());

        //sendMessageService.synUserInfo(synUser(user, appCode,depCode));
        ResultBean synUser = null;
        if (type == 0) {
            synUser = synUserService.addUser(orgNameList, orgIdList, roleIdList, userRole.getRoleNameList(),
                    userRole.getUsername(), userRole.getPassword(), userRole.getSalt(), userRole.getName(), appCode, userRole.getUsernames(), 1);
        } else if (type == 1) {
            synUser = synUserService.queryByUserName(appCode + "+" + user.getUsername());
            if (ResultBean.CODE_FAIL == synUser.getCode()) {
                throw new BizException(synUser.getErrMsg());
            }
            JSONObject jo = (JSONObject) synUser.getData();
            long userId = jo.getLong("id");
            synUser = synUserService.updateUser(orgNameList, orgIdList, roleIdList, userRole.getRoleNameList(),
                    userRole.getUsername(), userRole.getPassword(), userRole.getSalt(), userRole.getName(), appCode, userRole.getUsernames(), userId);
        }
        if (synUser == null) {
            throw new BizException("出现异常");
        }
        if (ResultBean.CODE_FAIL == synUser.getCode()) {
            throw new BizException(synUser.getErrMsg());
        }
    }

    public SynUser synUser(User user, String appCode, String depCode) throws BizException {
        SynUser synUser = new SynUser();
        BeanUtils.copyProperties(user, synUser);
        synUser.setAppCode(appCode);
        List orgCodeList = new ArrayList();
        orgCodeList.add(depCode);
        synUser.setOrgCodeList(orgCodeList);
        return synUser;
    }

    /**
     * 新增驾校后台用户
     *
     * @param userVo
     * @return
     * @throws Exception
     */
    public Map<String, Object> addBeanSchool(UserVo userVo, String appCode) throws Exception {
        if (StringUtils.isNotEmpty(userVo.getDepCodeB())) {
            userVo.setDepCode(userVo.getDepCodeB());
        } else if (StringUtils.isNotEmpty(userVo.getDepCodeF())) {
            userVo.setDepCode(userVo.getDepCodeF());
        }

        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", userVo.getUsername());
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user != null) {
            throw new BizException("账号已存在");
        }

        //用户
        user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        String password = PasswordUtils.createPassWord(8);
        //String ciphertext = PasswordUtils.getSaltMD5(password, slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);
        user.setType(Integer.valueOf(UserType.school.getValue().toString()));
        userMapper.insertObject(user);
        Long userId = user.getId();
        //用户部门
        DepartmentUser departmentUser = new DepartmentUser();
        departmentUser.setDepId(dep.getId());
        departmentUser.setUserId(userId);
        departmentUserMapper.insert(departmentUser);
        //用户岗位
        PositionUser positionUser = new PositionUser();
        positionUser.setPositionId(userVo.getPositionId());
        positionUser.setUserId(userId);
        positionUserMapper.insert(positionUser);

        //TODO 同步用户
        //sendMessageService.synUserInfo(synUser(user, appCode, dep.getDepCode()));
        addUser(user, appCode, dep.getDepCode(), userVo.getRoleId(), 0);

        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", password);
        return map;
    }

    public Map<String, Object> addBeanSchool(SchoolUserVo schoolUserVo, String appCode) throws Exception {
      /*  Map<String, Object> params = new HashMap<>();
        params.put("depCode", schoolUserVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }*/
        Long depId = schoolUserVo.getDepId();
        String depCode = schoolUserVo.getDepCode();
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", schoolUserVo.getUsername());
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user != null) {
            throw new BizException("账号已存在");
        }

        //用户
        user = new User();
        BeanUtils.copyProperties(schoolUserVo, user);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        String password = schoolUserVo.getPassword();
        // String ciphertext = PasswordUtils.getSaltMD5(password, slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);
        user.setType(Integer.valueOf(UserType.school.getValue().toString()));
        userMapper.insertObject(user);
        Long userId = user.getId();
        //用户部门
        DepartmentUser departmentUser = new DepartmentUser();
        departmentUser.setDepId(depId);
        departmentUser.setUserId(userId);
        departmentUserMapper.insert(departmentUser);

        //岗位
        Position position = new Position();
        position.setCreated(new Date());
        position.setDepId(depId);
        position.setIsDel(Integer.valueOf(IsDel.normal.getValue().toString()));
        position.setName("默认岗位");
        position.setRemarks("默认岗位");
        position.setCode(depCode + "00001");
        positionMapper.insertObject(position);
        Long positionId = position.getId();
        //用户岗位
        PositionUser positionUser = new PositionUser();
        positionUser.setPositionId(positionId);
        positionUser.setUserId(userId);
        positionUserMapper.insert(positionUser);

        //TODO 同步用户
        sendMessageService.synUserInfo(synUser(user, appCode, depCode));

        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", password);
        return map;
    }

    @Override
    public User findByName(String name) {
        List<User> list = userMapper.findByName(name);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response, String username, String password,
                                     String code, String captchaCode, String appCode) throws BizException {
        //TODO
        /*String captchaValue =  redisTemplate.opsForValue().get(captchaCode);
        if (captchaValue == null){
            throw new BizException("验证码失效");
        }
        if (captchaValue.equals(code)){
            redisTemplate.delete(captchaCode);
        }else{
            throw new BizException("验证码错误");
        }*/

        Condition condition = new Condition(User.class);
        condition.eqFiled("username", username);
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user == null) {
            throw new BizException("账号不存在");
        }
        //只能aos用户才能登录驾校系统
        if (!user.getType().equals(UserType.aos.getValue())) {
            throw new BizException("账号不存在");
        }
        if (user.getState().equals(UserStatus.del.getValue())) {
            throw new BizException("账号已被删除");
        }
        if (user.getState().equals(UserStatus.disable.getValue())) {
            throw new BizException("账号已被禁用");
        }
        /*String ciphertext = PasswordUtils.getSaltMD5(password, user.getSalt());
        if (!user.getPassword().equals(ciphertext)) {
            throw new BizException("密码错误");
        }
        CookieUtils.setCookie(request,response,GlobalConstant.cookieName,user.getId().toString(),GlobalConstant.cookieMaxAge,"UTF-8");*/
        //TODO 同步用户登录
        ResultBean o = synUserService.userLogin(appCode, username, password);
        if (ResultBean.CODE_FAIL == o.getCode()) {
            throw new BizException(o.getErrMsg());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("data", o.getData());
        return map;
    }

    /**
     * 退出登录
     *
     * @param token 登录用户token
     */
    public void logout(String token) throws BizException {
        ResultBean o = synUserService.userLoginOut(token);
        if (ResultBean.CODE_FAIL == o.getCode()) {
            throw new BizException(o.getErrMsg());
        }
    }

    /**
     * 分页查询
     *
     * @param pageIndex 当前页码
     * @param pageSize  每页显示条数
     * @param name      部门组织code
     * @param name      用户姓名
     * @param username  用户账号
     * @param depName   部门名称
     * @param type      用户类别 （1：傲雄  2：车管所  3：驾校 ）
     * @param userSate  用户状态
     * @return
     */
    @Override
    public IPage<UserDto> queryByPage(Integer pageIndex, Integer pageSize, String depCode, String name, String username,
                                      String depName, String type, String userSate) {
        Page<UserDto> pageBean = new Page<UserDto>(pageIndex, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("depCode", depCode);
        map.put("name", name);
        map.put("username", username);
        map.put("depName", depName);
        if (StringUtils.isNotEmpty(userSate)) {
            map.put("userSate", userSate);
        } else {
            map.put("state", UserStatus.normal.getValue());
        }
        map.put("type", type);
        map.put("pageBean", pageBean);
        List<UserDto> list = baseMapper.findByParams(map);
        IPage<UserDto> page = pageBean;
        page.setRecords(list);
        return page;
    }

    /**
     * 驾校账号信息统计
     *
     * @param depCode  部门code
     * @param depType  部门类型
     * @param userSate 用户状态
     * @return
     */
    public List<UserDto> selectByParamsSchool(String depCode, String depType, String userSate) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("depCode", depCode);
        params.put("depType", depType);
        List<UserDto> list = baseMapper.findByParams(params);
        return list;
    }

    /**
     * 驾校账号信息统计
     *
     * @param depCode  部门code
     * @param type     驾校类型
     * @param userSate 用户状态
     * @return
     */
    public Map<String, Object> selectByParams(String depCode, String type, String userSate) {
        Map<String, Object> map = new HashMap<>();
        //总校
        if (type.equals(SchoolType.gather.getValue().toString()) || type.equals(SchoolType.notgather.getValue().toString())) {
            String depType = DepartmentType.school.getValue().toString();
            List<UserDto> list = selectByParamsSchool(depCode, depType, userSate);
            map.put("school", list);
            map.put("schoolCount", list.size());
          /*  depType = DepartmentType.branch.getValue().toString();
            list = selectByParamsSchool(depCode, depType, userSate);
            map.put("branch", list);
            map.put("branchCount", list.size());
            depType = DepartmentType.point.getValue().toString();
            list = selectByParamsSchool(depCode, depType, userSate);
            map.put("point", list);
            map.put("pointCount", list.size());*/
        }
        //分校
        if (type.equals(SchoolType.branch.getValue().toString())) {
            String depType = DepartmentType.branch.getValue().toString();
            List<UserDto> list = selectByParamsSchool(depCode, depType, userSate);
            map.put("branch", list);
            map.put("branchCount", list.size());
            /*depType = DepartmentType.point.getValue().toString();
            list = selectByParamsSchool(depCode, depType, userSate);
            map.put("point", list);
            map.put("pointCount", list.size());*/
        }
        //报名点
        if (type.equals(SchoolType.registers.getValue().toString())) {
            String depType = DepartmentType.point.getValue().toString();
            List<UserDto> list = selectByParamsSchool(depCode, depType, userSate);
            map.put("point", list);
            map.put("pointCount", list.size());
        }
        return map;
    }

    public IPage<UserDto> queryByPage(Integer pageIndex, Integer pageSize, String depCode, String type, String userSate) {
        Page<UserDto> pageBean = new Page<UserDto>(pageIndex, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        if (type.equals(SchoolType.gather.getValue().toString()) || type.equals(SchoolType.notgather.getValue().toString())) {
            String depType = DepartmentType.school.getValue().toString();
            map.put("depCode", depCode);
            map.put("depType", depType);
        }
        if (type.equals(SchoolType.branch.getValue().toString())) {
            String depType = DepartmentType.branch.getValue().toString();
            map.put("depCode", depCode);
            map.put("depType", depType);
        }
        if (type.equals(SchoolType.registers.getValue().toString())) {
            String depType = DepartmentType.point.getValue().toString();
            map.put("depCode", depCode);
            map.put("depType", depType);
        }
        map.put("pageBean", pageBean);
        List<UserDto> list = baseMapper.findByParams(map);
        IPage<UserDto> page = pageBean;
        page.setRecords(list);
        return page;
    }

    /**
     * 删除用户
     *
     * @param id
     * @param appCode 应用code
     * @return
     */
    public int isDel(String id, String appCode) throws Exception {
        Condition condition = new Condition(User.class);
        condition.eqFiled("id", id);
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user == null) {
            throw new BizException("账号不存在");
        }
        user.setState(Integer.valueOf(UserStatus.del.getValue().toString()));
        user.setUpdated(new Date());
        int i = baseMapper.updateObject(user);

        //TODO 同步用户删除
        SynUser synUser = new SynUser();
        synUser.setAppCode(appCode);
        synUser.setUsername(user.getUsername());
        sendMessageService.deleteUser(synUser);
        return i;
    }

    /**
     * 修改驾校用户
     *
     * @param userVo
     * @param appCode 应用code
     * @return
     * @throws Exception
     */
    public int updateObjectSchool(UserVo userVo, String appCode) throws Exception {
        if (StringUtils.isNotEmpty(userVo.getDepCodeB())) {
            userVo.setDepCode(userVo.getDepCodeB());
        } else if (StringUtils.isNotEmpty(userVo.getDepCodeF())) {
            userVo.setDepCode(userVo.getDepCodeF());
        }

        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        User user = new User();
        user.setUpdated(new Date());
        user.setId(Long.valueOf(userVo.getId()));
        BeanUtils.copyProperties(userVo, user);
        //用户部门
        Condition condition = new Condition(DepartmentUser.class);
        condition.eqColumn("user_id", userVo.getId());
        DepartmentUser departmentUser = departmentUserMapper.selectOneBean(condition.getWrapper());
        if (!dep.getId().equals(departmentUser.getDepId())) {
            departmentUser.setDepId(dep.getId());
            departmentUserMapper.updateById(departmentUser);
        }
        //用户岗位
        condition = new Condition(PositionUser.class);
        condition.eqColumn("user_id", userVo.getId());
        PositionUser positionUser = positionUserMapper.selectOneBean(condition.getWrapper());
        if (!userVo.getPositionId().equals(positionUser.getPositionId())) {
            positionUser.setPositionId(userVo.getPositionId());
            positionUserMapper.updateById(positionUser);
        }
        //用户
        int i = baseMapper.updateObject(user);
        //TODO 同步用户
        addUser(user, appCode, dep.getDepCode(), userVo.getRoleId(), 1);

        return i;
    }

    /**
     * 修改用户
     *
     * @param userVo
     * @param appCode 应用code
     * @return
     * @throws Exception
     */
    public int updateObject(UserVo userVo, String appCode) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        Condition conditionUser = new Condition(User.class);
        conditionUser.eqFiled("id", userVo.getId());
        User user = baseMapper.selectOne(conditionUser.getWrapper());
        if (user == null) {
            throw new BizException("用户不存在");
        }
        user.setUpdated(new Date());
        BeanUtils.copyProperties(userVo, user);
        //用户部门
        Condition condition = new Condition(DepartmentUser.class);
        condition.eqColumn("user_id", userVo.getId());
        DepartmentUser departmentUser = departmentUserMapper.selectOneBean(condition.getWrapper());
        if (!dep.getId().equals(departmentUser.getDepId())) {
            departmentUser.setDepId(dep.getId());
            departmentUserMapper.updateById(departmentUser);
        }
        //用户岗位
        condition = new Condition(PositionUser.class);
        condition.eqColumn("user_id", userVo.getId());
        PositionUser positionUser = positionUserMapper.selectOneBean(condition.getWrapper());
        if (!userVo.getPositionId().equals(positionUser.getPositionId())) {
            positionUser.setPositionId(userVo.getPositionId());
            positionUserMapper.updateById(positionUser);
        }
        //用户
        int i = baseMapper.updateObject(user);
        //TODO 同步用户
        addUser(user, appCode, dep.getDepCode(), userVo.getRoleId(), 1);
        return i;
    }

    /**
     * 修改用户账号状态
     *
     * @param id    用户id
     * @param state 状态值
     * @return
     * @throws Exception
     */
    public int updateUserState(String id, String state) throws Exception {
        User user = new User();
        user.setId(Long.valueOf(id));
        if (UserStatus.normal.getValue().toString().equals(state)) {
            user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        } else if (UserStatus.disable.getValue().toString().equals(state)) {
            user.setState(Integer.valueOf(UserStatus.disable.getValue().toString()));
        }
        user.setUpdated(new Date());
        int i = baseMapper.updateObject(user);
        return i;
    }

    /**
     * 根据用户id查询
     *
     * @param id
     * @param appCode 应用code
     * @return
     */
    public UserDto findById(Long id, String appCode) throws BizException {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<UserDto> list = baseMapper.findByParams(params);
        if (list == null || list.size() == 0) {
            return null;
        }
        UserDto userDto = list.get(0);
        ResultBean synUser = synRoleService.getByUserName(appCode + "+" + userDto.getUsername());
        if (ResultBean.CODE_FAIL == synUser.getCode()) {
            throw new BizException(synUser.getErrMsg());
        }
        if (synUser.getData() != null) {
            JSONArray ja = (JSONArray) synUser.getData();
            JSONObject jo = ja.getJSONObject(0);
            long roleId = jo.getLong("id");
            userDto.setRoleId(roleId);
        }
        return userDto;
    }

    public UserDto findById(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<UserDto> list = baseMapper.findByParams(params);
        if (list == null || list.size() == 0) {
            return null;
        }
        UserDto userDto = list.get(0);
        return userDto;
    }

    /**
     * 根据驾校用户id查询
     *
     * @param id
     * @return
     */
    public UserDto findByIdSchool(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<UserDto> list = baseMapper.findByParams(params);
        if (list == null || list.size() == 0) {
            return null;
        }
        UserDto userDto = list.get(0);
        String depCode = userDto.getDepCode();

        if (DepartmentType.school.getValue().equals(userDto.getDepType())) {
            return userDto;
        }
        if (DepartmentType.branch.getValue().equals(userDto.getDepType())) {
            Map<String, Object> paramsDep = new HashMap<>();
            paramsDep.put("depCode", userDto.getParentCode());
            Department dep = departmentMapper.findByParams(paramsDep);
            userDto.setDepCodeF(userDto.getDepCode());
            userDto.setDepCodeFName(userDto.getDepName());
            userDto.setDepCode(dep.getDepCode());
            userDto.setDepName(dep.getName());
            return userDto;
        }
        if (DepartmentType.point.getValue().equals(userDto.getDepType())) {
            Map<String, Object> paramsDep = new HashMap<>();
            paramsDep.put("depCode", userDto.getParentCode());
            Department dep = departmentMapper.findByParams(paramsDep);
            if (DepartmentType.school.getValue().equals(dep.getDepType())) {
                userDto.setDepCodeFName(userDto.getDepName());
                userDto.setDepCodeF(userDto.getDepCode());
                userDto.setDepCode(dep.getDepCode());
                userDto.setDepName(dep.getName());
            } else if (DepartmentType.branch.getValue().equals(userDto.getDepType())) {
                userDto.setDepCodeB(userDto.getDepCode());
                userDto.setDepCodeBName(userDto.getDepName());
                userDto.setDepCodeFName(dep.getDepCode());
                userDto.setDepCodeF(dep.getName());

                paramsDep = new HashMap<>();
                paramsDep.put("depCode", dep.getParentCode());
                dep = departmentMapper.findByParams(paramsDep);
                userDto.setDepCode(dep.getDepCode());
                userDto.setDepName(dep.getName());
            }
            return userDto;
        }
        return null;
    }

    public User createNewUser(String name, String phone, String profilePhoto) {
        User bean = new User();
        bean.setName(name);
        baseMapper.insert(bean);
        return bean;
    }

    @Override
    public IPageBean<User> findByPage(IPageBean<User> page) {
        return baseMapper.selectPage(page, baseMapper.createQuery());
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, QueryWrapper<User> qw) {
        return null;
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, String name, String phone) {
        return null;
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, String name, String phone, Date startTime, Date endTime) {
        return null;
    }

    public User getById(long id) {
        return baseMapper.selectById(id);
    }

    public void update(User userInfo) {
        baseMapper.updateById(userInfo);
    }

    @Override
    public void updateInfo(long id, String name, String profilePhoto) {
        User userInfo = baseMapper.selectById(id);
        if (StringUtils.isNotBlank(name)) {
            userInfo.setName(name);
        }
        baseMapper.updateById(userInfo);
    }

    public User updatePhone(long id, String phone) {
        User userInfo = baseMapper.selectById(id);
        if (StringUtils.isNotBlank(phone)) {
            userInfo.setMobile(phone);
        }
        baseMapper.updateById(userInfo);
        return userInfo;
    }

    public int changePassword(String username, String password, String oldpassword, String currentUserId, String appCode) throws Exception {
        if (StringUtils.isEmpty(currentUserId)) {
            throw new BizException("请重新登录");
        }
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", username);
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user == null) {
            throw new BizException("账号不存在");
        }
        String oldpwd = PasswordUtils.getSaltMD5(oldpassword, user.getSalt());
        if (!oldpwd.equals(user.getPassword())) {
            throw new BizException("旧密码错误");
        }

        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        //String ciphertext = PasswordUtils.getSaltMD5(password, slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);

        //TODO 同步用户
        sendMessageService.synUserInfo(synUser(user, appCode, UserUtil.getUserDepCode(currentUserId)));
        return baseMapper.updateObject(user);
    }
}
